
<!DOCTYPE html>
<html lang="" class="loading">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>JavaOOP 21 - L3SLIE</title>
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="google" content="notranslate" />
    <meta name="keywords" content="L3SLIE,"> 
    <meta name="description" content="Welcome &amp; suit yourself,Java 异常处理异常是程序中的一些错误，但并不是所有的错误都是异常，并且错误有时候是可以避免的。
比如说，你的代码少了一个分号，那么运行出来结果是提示是错误 java.lang.Error；如果你,"> 
    <meta name="author" content="L3SLIE"> 
    <link rel="alternative" href="atom.xml" title="L3SLIE" type="application/atom+xml"> 
    <link rel="icon" href="/img/favicon.png"> 
    <link href="https://fonts.loli.net/css?family=Roboto+Mono|Rubik&display=swap" rel="stylesheet">
    
<link rel="stylesheet" href="//at.alicdn.com/t/font_1429596_nzgqgvnmkjb.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/animate.css/3.7.2/animate.min.css">

    
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/codemirror.min.css">

    
<link rel="stylesheet" href="//cdn.bootcss.com/codemirror/5.48.4/theme/dracula.css">

    
<link rel="stylesheet" href="/css/obsidian.css">

    
<link rel="stylesheet" href="/css/ball-atom.min.css">

<meta name="generator" content="Hexo 4.2.0"></head>


<body class="loading">
    <div class="loader">
        <div class="la-ball-atom la-2x">
            <div></div>
            <div></div>
            <div></div>
            <div></div>
        </div>
    </div>
    <span id="config-title" style="display:none">L3SLIE</span>
    <div id="loader"></div>
    <div id="single">
    <div class="scrollbar gradient-bg-rev"></div>
<div id="top" style="display: block;">
    <div class="bar" style="width: 0;"></div>
    <div class="navigation animated fadeIn fast delay-1s">
        <img id="home-icon" class="icon-home" src="/img/favicon.png" alt="" data-url="http://l3slie.gitee.io">
        <div id="play-icon" title="Play/Pause" class="iconfont icon-play"></div>
        <h3 class="subtitle">JavaOOP 21</h3>
        <div class="social">
            <!--        <div class="like-icon">-->
            <!--            <a href="javascript:;" class="likeThis active"><span class="icon-like"></span><span class="count">76</span></a>-->
            <!--        </div>-->
            <div>
                <div class="share">
                    
                        <a href="javascript:;" class="iconfont icon-share1"></a>
                        <div class="share-component-cc" data-disabled="facebook,douban,linkedin,diandian,tencent,google"></div>
                    
                </div>
            </div>
        </div>
    </div>
</div>

    <div class="section">
        <div class=article-header-wrapper>
    <div class="article-header">
        <div class="article-cover animated fadeIn" style="
            animation-delay: 600ms;
            animation-duration: 1.2s;
            background-image: 
                radial-gradient(ellipse closest-side, rgba(0, 0, 0, 0.65), #100e17),
                url(/img/cover1.jpg) ">
        </div>
        <div class="else">
            <p class="animated fadeInDown">
                
                <a href="/categories/JAVA"><b>「
                    </b>JAVA<b> 」</b></a>
                
                April 02, 2020
            </p>
            <h3 class="post-title animated fadeInDown"><a href="/2020/04/02/JavaOOP-21/" title="JavaOOP 21" class="">JavaOOP 21</a>
            </h3>
            
            <p class="post-count animated fadeInDown">
                
                <span>
                    <b class="iconfont icon-text2"></b> <i>Words count</i>
                    13k
                </span>
                
                
                <span>
                    <b class="iconfont icon-timer__s"></b> <i>Reading time</i>
                    12 mins.
                </span>
                
                
                <span id="/2020/04/02/JavaOOP-21/" class="leancloud_visitors" data-flag-title="JavaOOP 21">
                    <b class="iconfont icon-read"></b> <i>Read count</i>
                    <span class="leancloud-visitors-count">100000</span>
                </span>
                
                
            </p>
            
            
            <ul class="animated fadeInDown post-tags-list" itemprop="keywords"><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/JAVA/" rel="tag">JAVA</a></li><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/NOTE/" rel="tag">NOTE</a></li><li class="animated fadeInDown post-tags-list-item"><a class="animated fadeInDown post-tags-list-link" href="/tags/%E9%9D%A2%E5%AF%B9%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B/" rel="tag">面对对象编程</a></li></ul>
            
        </div>
    </div>
</div>

<div class="screen-gradient-after">
    <div class="screen-gradient-content">
        <div class="screen-gradient-content-inside">
            <div class="bold-underline-links screen-gradient-sponsor">
                <p>
                    <span class="animated fadeIn delay-1s"></span>
                </p>
            </div>
        </div>
    </div>
</div>

<div class="article">
    <div class='main'>
        <div class="content markdown animated fadeIn">
            <h1 id="Java-异常处理"><a href="#Java-异常处理" class="headerlink" title="Java 异常处理"></a>Java 异常处理</h1><p>异常是程序中的一些错误，但并不是所有的错误都是异常，并且错误有时候是可以避免的。</p>
<p>比如说，你的代码少了一个分号，那么运行出来结果是提示是错误 java.lang.Error；如果你用System.out.println(11/0)，那么你是因为你用0做了除数，会抛出 java.lang.ArithmeticException 的异常。</p>
<p>异常发生的原因有很多，通常包含以下几大类：</p>
<ul>
<li>用户输入了非法数据。</li>
<li>要打开的文件不存在。</li>
<li>网络通信时连接中断，或者JVM内存溢出。</li>
</ul>
<p>这些异常有的是因为用户错误引起，有的是程序错误引起的，还有其它一些是因为物理错误引起的。-</p>
<p>要理解Java异常处理是如何工作的，你需要掌握以下三种类型的异常：</p>
<ul>
<li><strong>检查性异常：</strong>最具代表的检查性异常是用户错误或问题引起的异常，这是程序员无法预见的。例如要打开一个不存在文件时，一个异常就发生了，这些异常在编译时不能被简单地忽略。</li>
<li><strong>运行时异常：</strong> 运行时异常是可能被程序员避免的异常。与检查性异常相反，运行时异常可以在编译时被忽略。</li>
<li><strong>错误：</strong> 错误不是异常，而是脱离程序员控制的问题。错误在代码中通常被忽略。例如，当栈溢出时，一个错误就发生了，它们在编译也检查不到的。</li>
</ul>
<hr>
<h2 id="Exception-类的层次"><a href="#Exception-类的层次" class="headerlink" title="Exception 类的层次"></a>Exception 类的层次</h2><blockquote>
<p>所有的异常类是从 java.lang.Exception 类继承的子类。</p>
</blockquote>
<p>Exception 类是 Throwable 类的子类。除了Exception类外，Throwable还有一个子类Error 。</p>
<p>Java 程序通常不捕获错误。错误一般发生在严重故障时，它们在Java程序处理的范畴之外。</p>
<p>Error 用来指示运行时环境发生的错误。</p>
<p>例如，JVM 内存溢出。一般地，程序不会从错误中恢复。</p>
<p>异常类有两个主要的子类：IOException 类和 RuntimeException 类。</p>
<p><img src="https://www.runoob.com/wp-content/uploads/2013/12/12-130Q1234I6223.jpg" alt="img"></p>
<p>在 Java 内置类中(接下来会说明)，有大部分常用检查性和非检查性异常。</p>
<hr>
<h2 id="Java-内置异常类"><a href="#Java-内置异常类" class="headerlink" title="Java 内置异常类"></a>Java 内置异常类</h2><p>Java 语言定义了一些异常类在 java.lang 标准包中。</p>
<p>标准运行时异常类的子类是最常见的异常类。由于 java.lang 包是默认加载到所有的 Java 程序的，所以大部分从运行时异常类继承而来的异常都可以直接使用。</p>
<p>Java 根据各个类库也定义了一些其他的异常，下面的表中列出了 Java 的非检查性异常。</p>
<table>
<thead>
<tr>
<th align="left"><strong>异常</strong></th>
<th align="left"><strong>描述</strong></th>
</tr>
</thead>
<tbody><tr>
<td align="left">ArithmeticException</td>
<td align="left">当出现<code>异常的运算条件</code>时，抛出此异常。例如，一个整数”除以零”时，抛出此类的一个实例。</td>
</tr>
<tr>
<td align="left">ArrayIndexOutOfBoundsException</td>
<td align="left">用<code>非法索引访问数组</code>时抛出的异常。如果索引为负或大于等于数组大小，则该索引为非法索引。</td>
</tr>
<tr>
<td align="left">ArrayStoreException</td>
<td align="left">试图将错误类型的对象存储到一个对象数组时抛出的异常。</td>
</tr>
<tr>
<td align="left">ClassCastException</td>
<td align="left">当试图将对象强制转换为不是实例的子类时，抛出该异常。</td>
</tr>
<tr>
<td align="left">IllegalArgumentException</td>
<td align="left">抛出的异常表明向方法传递了一个不合法或不正确的参数。</td>
</tr>
<tr>
<td align="left">IllegalMonitorStateException</td>
<td align="left">抛出的异常表明某一线程已经试图等待对象的监视器，或者试图通知其他正在等待对象的监视器而本身没有指定监视器的线程。</td>
</tr>
<tr>
<td align="left">IllegalStateException</td>
<td align="left">在非法或不适当的时间调用方法时产生的信号。换句话说，即 Java 环境或 Java 应用程序没有处于请求操作所要求的适当状态下。</td>
</tr>
<tr>
<td align="left">IllegalThreadStateException</td>
<td align="left">线程没有处于请求操作所要求的适当状态时抛出的异常。</td>
</tr>
<tr>
<td align="left">IndexOutOfBoundsException</td>
<td align="left">指示某排序索引（例如对数组、字符串或向量的排序）超出范围时抛出。</td>
</tr>
<tr>
<td align="left">NegativeArraySizeException</td>
<td align="left">如果应用程序试图创建大小为负的数组，则抛出该异常。</td>
</tr>
<tr>
<td align="left">NullPointerException</td>
<td align="left">当应用程序试图在需要对象的地方使用 <code>null</code> 时，抛出该异常</td>
</tr>
<tr>
<td align="left">NumberFormatException</td>
<td align="left">当应用程序试图将字符串转换成一种数值类型，但该字符串不能转换为适当格式时，抛出该异常。</td>
</tr>
<tr>
<td align="left">SecurityException</td>
<td align="left">由安全管理器抛出的异常，指示存在安全侵犯。</td>
</tr>
<tr>
<td align="left">StringIndexOutOfBoundsException</td>
<td align="left">此异常由 <code>String</code> 方法抛出，指示索引或者为负，或者超出字符串的大小。</td>
</tr>
<tr>
<td align="left">UnsupportedOperationException</td>
<td align="left">当不支持请求的操作时，抛出该异常。</td>
</tr>
</tbody></table>
<p>下面的表中列出了 Java 定义在 java.lang 包中的检查性异常类。</p>
<table>
<thead>
<tr>
<th align="left"><strong>异常</strong></th>
<th align="left"><strong>描述</strong></th>
</tr>
</thead>
<tbody><tr>
<td align="left">ClassNotFoundException</td>
<td align="left">应用程序试图加载类时，找不到相应的类，抛出该异常。</td>
</tr>
<tr>
<td align="left">CloneNotSupportedException</td>
<td align="left">当调用 <code>Object</code> 类中的 <code>clone</code> 方法克隆对象，但该对象的类无法实现 <code>Cloneable</code> 接口时，抛出该异常。</td>
</tr>
<tr>
<td align="left">IllegalAccessException</td>
<td align="left">拒绝访问一个类的时候，抛出该异常。</td>
</tr>
<tr>
<td align="left">InstantiationException</td>
<td align="left">当试图使用 <code>Class</code> 类中的 <code>newInstance</code> 方法创建一个类的实例，而指定的类对象因为是一个接口或是一个抽象类而无法实例化时，抛出该异常。</td>
</tr>
<tr>
<td align="left">InterruptedException</td>
<td align="left">一个线程被另一个线程中断，抛出该异常。</td>
</tr>
<tr>
<td align="left">NoSuchFieldException</td>
<td align="left">请求的变量不存在</td>
</tr>
<tr>
<td align="left">NoSuchMethodException</td>
<td align="left">请求的方法不存在</td>
</tr>
</tbody></table>
<hr>
<h2 id="异常方法"><a href="#异常方法" class="headerlink" title="异常方法"></a>异常方法</h2><p>下面的列表是 Throwable 类的主要方法:</p>
<table>
<thead>
<tr>
<th align="left"><strong>序号</strong></th>
<th align="left"><strong>方法及说明</strong></th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left"><strong>public String getMessage()</strong> 返回关于发生的异常的详细信息。这个消息在Throwable 类的构造函数中初始化了。</td>
</tr>
<tr>
<td align="left">2</td>
<td align="left"><strong>public Throwable getCause()</strong> 返回一个Throwable 对象代表异常原因。</td>
</tr>
<tr>
<td align="left">3</td>
<td align="left"><strong>public String toString()</strong> 使用getMessage()的结果返回类的串级名字。</td>
</tr>
<tr>
<td align="left">4</td>
<td align="left"><strong>public void printStackTrace()</strong> 打印toString()结果和栈层次到System.err，即错误输出流。</td>
</tr>
<tr>
<td align="left">5</td>
<td align="left"><strong>public StackTraceElement [] getStackTrace()</strong> 返回一个包含堆栈层次的数组。下标为0的元素代表栈顶，最后一个元素代表方法调用堆栈的栈底。</td>
</tr>
<tr>
<td align="left">6</td>
<td align="left"><strong>public Throwable fillInStackTrace()</strong> 用当前的调用栈层次填充Throwable 对象栈层次，添加到栈层次任何先前信息中。</td>
</tr>
</tbody></table>
<hr>
<h2 id="捕获异常"><a href="#捕获异常" class="headerlink" title="捕获异常"></a>捕获异常</h2><p>使用 try 和 catch 关键字可以捕获异常。try/catch 代码块放在异常可能发生的地方。</p>
<p>try/catch代码块中的代码称为保护代码，使用 try/catch 的语法如下：</p>
<pre><code class="java">try
{
   // 程序代码
}catch(ExceptionName e1)
{
   //Catch 块
}</code></pre>
<p>Catch 语句包含要捕获异常类型的声明。当保护代码块中发生一个异常时，try 后面的 catch 块就会被检查。</p>
<p>如果发生的异常包含在 catch 块中，异常会被传递到该 catch 块，这和传递一个参数到方法是一样。</p>
<h3 id="实例"><a href="#实例" class="headerlink" title="实例"></a>实例</h3><p>下面的例子中声明有两个元素的一个数组，当代码试图访问数组的第三个元素的时候就会抛出一个异常。</p>
<pre><code class="java">// 文件名 : ExcepTest.java
import java.io.*;
public class ExcepTest{

   public static void main(String args[]){
      try{
         int a[] = new int[2];
         System.out.println(&quot;Access element three :&quot; + a[3]);
      }catch(ArrayIndexOutOfBoundsException e){
         System.out.println(&quot;Exception thrown  :&quot; + e);
      }
      System.out.println(&quot;Out of the block&quot;);
   }
}</code></pre>
<p>以上代码编译运行输出结果如下：</p>
<pre><code class="java">Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block</code></pre>
<hr>
<h2 id="多重捕获块"><a href="#多重捕获块" class="headerlink" title="多重捕获块"></a>多重捕获块</h2><p>一个 try 代码块后面跟随多个 catch 代码块的情况就叫多重捕获。</p>
<p>多重捕获块的语法如下所示：</p>
<pre><code class="java">try{
   // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}</code></pre>
<p>上面的代码段包含了 3 个 catch块。</p>
<p>可以在 try 语句后面添加任意数量的 catch 块。</p>
<p>如果保护代码中发生异常，异常被抛给第一个 catch 块。</p>
<p>如果抛出异常的数据类型与 ExceptionType1 匹配，它在这里就会被捕获。</p>
<p>如果不匹配，它会被传递给第二个 catch 块。</p>
<p>如此，直到异常被捕获或者通过所有的 catch 块。</p>
<h3 id="实例-1"><a href="#实例-1" class="headerlink" title="实例"></a>实例</h3><p>该实例展示了怎么使用多重 try/catch。</p>
<pre><code class="java">try {
    file = new FileInputStream(fileName);
    x = (byte) file.read();
} catch(FileNotFoundException f) { // Not valid!
    f.printStackTrace();
    return -1;
} catch(IOException i) {
    i.printStackTrace();
    return -1;
}</code></pre>
<hr>
<h2 id="throws-throw-关键字："><a href="#throws-throw-关键字：" class="headerlink" title="throws/throw 关键字："></a>throws/throw 关键字：</h2><p>如果一个方法没有捕获到一个检查性异常，那么该方法必须使用 throws 关键字来声明。throws 关键字放在方法签名的尾部。</p>
<p>也可以使用 throw 关键字抛出一个异常，无论它是新实例化的还是刚捕获到的。</p>
<p>下面方法的声明抛出一个 RemoteException 异常：</p>
<pre><code class="java">import java.io.*;
public class className
{
  public void deposit(double amount) throws RemoteException
  {
    // Method implementation
    throw new RemoteException();
  }
  //Remainder of class definition
}</code></pre>
<p>一个方法可以声明抛出多个异常，多个异常之间用逗号隔开。</p>
<p>例如，下面的方法声明抛出 RemoteException 和 InsufficientFundsException：</p>
<pre><code class="java">import java.io.*;
public class className
{
   public void withdraw(double amount) throws RemoteException,
                              InsufficientFundsException
   {
       // Method implementation
   }
   //Remainder of class definition
}</code></pre>
<hr>
<h2 id="finally关键字"><a href="#finally关键字" class="headerlink" title="finally关键字"></a>finally关键字</h2><p>finally 关键字用来创建在 try 代码块后面执行的代码块。</p>
<p><code>无论是否发生异常，finally 代码块中的代码总会被执行</code>。</p>
<p>在 finally 代码块中，可以运行清理类型等收尾善后性质的语句。</p>
<p>finally 代码块出现在 catch 代码块最后，语法如下：</p>
<pre><code class="java">try{
  // 程序代码
}catch(异常类型1 异常的变量名1){
  // 程序代码
}catch(异常类型2 异常的变量名2){
  // 程序代码
}finally{
  // 程序代码
}</code></pre>
<h3 id="实例-2"><a href="#实例-2" class="headerlink" title="实例"></a>实例</h3><pre><code class="java">public class ExcepTest{
  public static void main(String args[]){
    int a[] = new int[2];
    try{
       System.out.println(&quot;Access element three :&quot; + a[3]);
    }catch(ArrayIndexOutOfBoundsException e){
       System.out.println(&quot;Exception thrown  :&quot; + e);
    }
    finally{
       a[0] = 6;
       System.out.println(&quot;First element value: &quot; +a[0]);
       System.out.println(&quot;The finally statement is executed&quot;);
    }
  }
}</code></pre>
<p>以上实例编译运行结果如下：</p>
<pre><code class="java">Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3
First element value: 6
The finally statement is executed</code></pre>
<p>注意下面事项：</p>
<ul>
<li>catch 不能独立于 try 存在。</li>
<li>在 try/catch 后面添加 finally 块并非强制性要求的。</li>
<li>try 代码后不能既没 catch 块也没 finally 块。</li>
<li>try, catch, finally 块之间不能添加任何代码。</li>
</ul>
<hr>
<h2 id="声明自定义异常"><a href="#声明自定义异常" class="headerlink" title="声明自定义异常"></a>声明自定义异常</h2><p>在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。</p>
<ul>
<li>所有异常都必须是 Throwable 的子类。</li>
<li>如果希望写一个检查性异常类，则需要继承 Exception 类。</li>
<li>如果你想写一个运行时异常类，那么需要继承 RuntimeException 类。</li>
</ul>
<p>可以像下面这样定义自己的异常类：</p>
<pre><code class="java">class MyException extends Exception{
}</code></pre>
<p>只继承Exception 类来创建的异常类是检查性异常类。</p>
<p>下面的 InsufficientFundsException 类是用户定义的异常类，它继承自 Exception。</p>
<p>一个异常类和其它任何类一样，包含有变量和方法。</p>
<h3 id="实例-3"><a href="#实例-3" class="headerlink" title="实例"></a>实例</h3><p>以下实例是一个银行账户的模拟，通过银行卡的号码完成识别，可以进行存钱和取钱的操作。</p>
<pre><code class="java">// 文件名InsufficientFundsException.java
import java.io.*;

//自定义异常类，继承Exception类
public class InsufficientFundsException extends Exception
{
  //此处的amount用来储存当出现异常（取出钱多于余额时）所缺乏的钱
  private double amount;
  public InsufficientFundsException(double amount)
  {
    this.amount = amount;
  } 
  public double getAmount()
  {
    return amount;
  }
}</code></pre>
<p>为了展示如何使用我们自定义的异常类，</p>
<p>在下面的 CheckingAccount 类中包含一个 withdraw() 方法抛出一个 InsufficientFundsException 异常。</p>
<pre><code class="java">// 文件名称 CheckingAccount.java
import java.io.*;

//此类模拟银行账户
public class CheckingAccount
{
  //balance为余额，number为卡号
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
  //方法：存钱
   public void deposit(double amount)
   {
      balance += amount;
   }
  //方法：取钱
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount &lt;= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
  //方法：返回余额
   public double getBalance()
   {
      return balance;
   }
  //方法：返回卡号
   public int getNumber()
   {
      return number;
   }
}</code></pre>
<p>下面的 BankDemo 程序示范了如何调用 CheckingAccount 类的 deposit() 和 withdraw() 方法。</p>
<pre><code class="java">//文件名称 BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println(&quot;Depositing $500...&quot;);
      c.deposit(500.00);
      try
      {
         System.out.println(&quot;\nWithdrawing $100...&quot;);
         c.withdraw(100.00);
         System.out.println(&quot;\nWithdrawing $600...&quot;);
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println(&quot;Sorry, but you are short $&quot;
                                  + e.getAmount());
         e.printStackTrace();
      }
    }
}</code></pre>
<p>编译上面三个文件，并运行程序 BankDemo，得到结果如下所示：</p>
<pre><code class="java">Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)</code></pre>
<hr>
<h2 id="通用异常"><a href="#通用异常" class="headerlink" title="通用异常"></a>通用异常</h2><p>在Java中定义了两种类型的异常和错误。</p>
<ul>
<li><strong>JVM(Java虚拟机<em>) *</em>异常：</strong>由 JVM 抛出的异常或错误。例如：NullPointerException 类，ArrayIndexOutOfBoundsException 类，ClassCastException 类。</li>
<li><strong>程序级异常：</strong>由程序或者API程序抛出的异常。例如 IllegalArgumentException 类，IllegalStateException 类。</li>
</ul>
<h1 id="–NEXT–"><a href="#–NEXT–" class="headerlink" title="–NEXT–"></a>–NEXT–</h1><p>Java继承。</p>

            <!--[if lt IE 9]><script>document.createElement('audio');</script><![endif]-->
            <audio id="audio" loop="1" preload="auto" controls="controls"
                data-autoplay="false">
                <source type="audio/mpeg" src="">
            </audio>
            
            <ul id="audio-list" style="display:none">
                
                
                <li title='0' data-url='/statics/i saw you in a dream.mp3'></li>
                
                    
            </ul>
            
            
            
            <div id="vcomments"></div>
            
        </div>
        <div class="sidebar">
            <div class="box animated fadeInRight">
                <div class="subbox">
                    <img src="/img/avatar.jpg" height=300 width=300></img>
                    <p>L3SLIE</p>
                    <span>Life Long & Pwn</span>
                    <dl>
                        <dd><a href="https://github.com/13slie" target="_blank"><span
                                    class=" iconfont icon-github"></span></a></dd>
                        <dd><a href="" target="_blank"><span
                                    class=" iconfont icon-twitter"></span></a></dd>
                        <dd><a href="https://stackexchange.com/users/17805607/l3slie" target="_blank"><span
                                    class=" iconfont icon-stack-overflow"></span></a></dd>
                    </dl>
                </div>
                <ul>
                    <li><a href="/">46 <p>Articles</p></a></li>
                    <li><a href="/categories">13 <p>Categories</p></a></li>
                    <li><a href="/tags">20 <p>Tags</p></a></li>
                    <br><span><b><p>友链博客</p></b></span><br>
                    <span><u><p><a href="http://rdd.xjusec.club/" target="_blank">Rdd</a></p></u></span>
                    <span><u><p><a href="http://www.xjusec.club/" target="_blank">XJUSEC</a></p></u></span>
                    <span><u><p><a href="http://www.r1ght0us.xyz/" target="_blank">r1ght0us</a></p></u></span>
                </ul>
            </div>
            
            
            
            <div class="box sticky animated fadeInRight faster">
                <div id="toc" class="subbox">
                    <h4>Contents</h4>
                    <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Java-异常处理"><span class="toc-number">1.</span> <span class="toc-text">Java 异常处理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Exception-类的层次"><span class="toc-number">1.1.</span> <span class="toc-text">Exception 类的层次</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Java-内置异常类"><span class="toc-number">1.2.</span> <span class="toc-text">Java 内置异常类</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#异常方法"><span class="toc-number">1.3.</span> <span class="toc-text">异常方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#捕获异常"><span class="toc-number">1.4.</span> <span class="toc-text">捕获异常</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#实例"><span class="toc-number">1.4.1.</span> <span class="toc-text">实例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#多重捕获块"><span class="toc-number">1.5.</span> <span class="toc-text">多重捕获块</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#实例-1"><span class="toc-number">1.5.1.</span> <span class="toc-text">实例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#throws-throw-关键字："><span class="toc-number">1.6.</span> <span class="toc-text">throws&#x2F;throw 关键字：</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#finally关键字"><span class="toc-number">1.7.</span> <span class="toc-text">finally关键字</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#实例-2"><span class="toc-number">1.7.1.</span> <span class="toc-text">实例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#声明自定义异常"><span class="toc-number">1.8.</span> <span class="toc-text">声明自定义异常</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#实例-3"><span class="toc-number">1.8.1.</span> <span class="toc-text">实例</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#通用异常"><span class="toc-number">1.9.</span> <span class="toc-text">通用异常</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#–NEXT–"><span class="toc-number">2.</span> <span class="toc-text">–NEXT–</span></a></li></ol>
                </div>
            </div>
            
            
        </div>
    </div>
</div>

    </div>
</div>
    <div id="back-to-top" class="animated fadeIn faster">
        <div class="flow"></div>
        <span class="percentage animated fadeIn faster">0%</span>
        <span class="iconfont icon-top02 animated fadeIn faster"></span>
    </div>
</body>
<footer>
    <p class="copyright" id="copyright">
		<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
		<script>
		var now = new Date(); 
		function createtime() { 
			var grt= new Date("01/10/2020 00:00:00");//在此处修改你的建站时间
			now.setTime(now.getTime()+250); 
			days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days); 
			hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours); 
			if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum); 
			mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;} 
			seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum); 
			snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;} 
			document.getElementById("timeDate").innerHTML = "本站已安全运行 "+dnum+" 天 "; 
			document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒"; 
		} 
		setInterval("createtime()",250);
		</script>
        &copy; 2020
        <span class="gradient-text">
            L3SLIE
        </span>❤
        Powered by <a href="http://hexo.io/" title="Hexo" target="_blank" rel="noopener">Hexo</a>
        Theme
        <span class="gradient-text">
            <a href="https://github.com/TriDiamond/hexo-theme-obsidian" title="Obsidian" target="_blank" rel="noopener">Obsidian</a>
        </span>
        <small><a href="https://github.com/TriDiamond/hexo-theme-obsidian/blob/master/CHANGELOG.md" title="v1.4.3" target="_blank" rel="noopener">v1.4.3</a></small>
    </p>
</footer>

<script type="text/javascript" src="https://cdn.bootcss.com/mathjax/2.7.6/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<script>
  MathJax.Hub.Config({
    "HTML-CSS": {
      preferredFont: "TeX",
      availableFonts: ["STIX", "TeX"],
      linebreaks: {
        automatic: true
      },
      EqnChunk: (MathJax.Hub.Browser.isMobile ? 10 : 50)
    },
    tex2jax: {
      inlineMath: [
        ["$", "$"],
        ["\\(", "\\)"]
      ],
      processEscapes: true,
      ignoreClass: "tex2jax_ignore|dno",
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      noUndefined: {
        attributes: {
          mathcolor: "red",
          mathbackground: "#FFEEEE",
          mathsize: "90%"
        }
      },
      Macros: {
        href: "{}"
      }
    },
    messageStyle: "none"
  });
</script>
<script>
  function initialMathJax() {
    MathJax.Hub.Queue(function () {
      var all = MathJax.Hub.getAllJax(),
        i;
      // console.log(all);
      for (i = 0; i < all.length; i += 1) {
        console.log(all[i].SourceElement().parentNode)
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
    });
  }

  function reprocessMathJax() {
    if (typeof MathJax !== 'undefined') {
      MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
    }
  }
</script>




<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="/js/plugin.js"></script>
<script src="/js/obsidian.js"></script>
<script src="/js/jquery.truncate.js"></script>
<script src="/js/search.js"></script>


<script src="//cdn.bootcss.com/typed.js/2.0.10/typed.min.js"></script>


<script src="//cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script>


<script src="//cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js"></script>


<script src="https://cdn.bootcss.com/codemirror/5.48.4/codemirror.min.js"></script>

    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/javascript/javascript.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/css/css.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/xml/xml.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/htmlmixed/htmlmixed.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/clike/clike.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/php/php.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/shell/shell.min.js"></script>


    
<script src="//cdn.bootcss.com/codemirror/5.48.4/mode/python/python.min.js"></script>




    
<script src="/js/busuanzi.min.js"></script>

    <script>
        $(document).ready(function () {
            if ($('span[id^="busuanzi_"]').length) {
                initialBusuanzi();
            }
        });
    </script>



<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.css">
<link rel="stylesheet" href="//cdn.bootcss.com/photoswipe/4.1.3/default-skin/default-skin.min.css">


<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe.min.js"></script>
<script src="//cdn.bootcss.com/photoswipe/4.1.3/photoswipe-ui-default.min.js"></script>


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>
    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">
        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <!--  Controls are self-explanatory. Order can be changed. -->
                <div class="pswp__counter"></div>
                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
                <button class="pswp__button pswp__button--share" title="Share"></button>
                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                      <div class="pswp__preloader__cut">
                        <div class="pswp__preloader__donut"></div>
                      </div>
                    </div>
                </div>
            </div>
            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div> 
            </div>
            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>
            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>
            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>
        </div>
    </div>
</div>







<script>
    function initialTyped () {
        var typedTextEl = $('.typed-text');
        if (typedTextEl && typedTextEl.length > 0) {
            var typed = new Typed('.typed-text', {
                strings: ["Life Long &amp; Pwn", "生命不息，破解不止"],
                typeSpeed: 90,
                loop: true,
                loopCount: Infinity,
                backSpeed: 20,
            });
        }
    }

    if ($('.article-header') && $('.article-header').length) {
        $(document).ready(function () {
            initialTyped();
        });
    }
</script>


    
<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

    <script>

        var valine = new Valine();

        function initValine(path) {
            if (!path) path = window.location.pathname;
            let language = '';
            if (!language) {
                language = 'en';
            } else {
                language = language.toLowerCase();
            }
            valine.init({
                el: '#vcomments',
                appId: 'GnPlbHQ9xAWEoCDC8rR3zALj-gzGzoHsz',
                appKey: 'Nygd2awSxr9ioTDtvbH6hE0l',
                notify: 'false',
                verify: 'false',
                avatar: 'mm',
                placeholder: 'feel free to comment~',
                visitor: 'true',
                path: path,
                lang: language
            });
        }

        $(document).ready(function () {
            initValine();
        });
    </script>



</html>
<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/love.js"></script>
<!-- 烟火效果 -->
<canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;" ></canvas> 
<script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
<script type="text/javascript" src="/js/fireworks.js"></script>
<!--自定义标题-->
<script type="text/javascript" src="\js\title.js"></script>
